package com.jumper.study.common.util;

import jakarta.servlet.http.HttpServletRequest;

/*
 * 请求工具
 */
public final class RequestUtil {
    //获取IP地址
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        //多代理转发下，多个IP会用,分割，获取第一个即可
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }

        return ip;
    }

    //获取浏览器user-agent
    public static String getAgent(HttpServletRequest request) {
        return request.getHeader("user-agent");
    }
}
